package com.example.demo.service.impl;

import com.example.demo.dto.NewTaskFlowDTO;
import com.example.demo.dto.ProcessNodeDTO;
import com.example.demo.dto.TaskApprovalNodeDetailDTO;
import com.example.demo.dto.TaskApprovalStatusDTO;
import com.example.demo.dto.TaskApprovalWithRawDataDTO;
import com.example.demo.dto.UserTaskStatisticsDTO;
import com.example.demo.dto.DataSourceUserStatisticsDTO;
import com.example.demo.dto.UserApprovalStatisticsDTO;
import com.example.demo.dto.DataSourceTaskStatisticsDTO;
import com.example.demo.entity.User;
import com.example.demo.entity.DataSource;
import com.example.demo.entity.NewTask;
import com.example.demo.entity.ProcessNode;
import com.example.demo.entity.TaskApprovalStatus;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.DataSourceMapper;
import com.example.demo.mapper.NewTaskMapper;
import com.example.demo.mapper.ProcessConfigMapper;
import com.example.demo.mapper.ProcessNodeMapper;
import com.example.demo.mapper.TaskApprovalStatusMapper;
import com.example.demo.mapper.TaskTypeMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.request.ApproveTaskRequest;
import com.example.demo.request.CreateTaskApprovalStatusRequest;
import com.example.demo.request.ForwardTaskRequest;
import com.example.demo.service.NewTaskFlowService;
import com.example.demo.service.NewTaskService;
import com.example.demo.service.ProcessNodeService;
import com.example.demo.service.TaskApprovalStatusService;
//import org.slf4j.logger;
//import org.slf4j.loggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TaskApprovalStatusServiceImpl implements TaskApprovalStatusService {
//    private static final logger log = loggerFactory.getlogger(TaskApprovalStatusServiceImpl.class);

    @Autowired
    private TaskApprovalStatusMapper taskApprovalStatusMapper;

    @Autowired
    private NewTaskFlowService newTaskFlowService;

    @Autowired
    private ProcessNodeService processNodeService;

    @Autowired
    private NewTaskMapper newTaskMapper;

    @Autowired
    private DataSourceMapper dataSourceMapper;

    @Autowired
    private ProcessNodeMapper processNodeMapper;

    @Autowired
    private ProcessConfigMapper processConfigMapper;

    @Autowired
    private NewTaskService newTaskService;

    @Autowired
    private TaskTypeMapper taskTypeMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<TaskApprovalStatusDTO> getTaskApprovalStatuses(int page, int size, Long taskId, Long flowId) {
        int offset = page * size;
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper.selectPage(offset, size, taskId,
                flowId);
        return taskApprovalStatuses.stream()
                .map(entity -> {
                    TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(entity);
                    fillNameFields(dto, entity);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskApprovalWithRawDataDTO> getTaskApprovalStatusesByApproverIdAndStatusProcessingWithRawData(
            Long approverId) {
        //log.info("查询审批人ID={}的处理中审批任务(包含原始数据)", approverId);
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper
                .selectByApproverIdAndStatusProcessing(approverId);
        //log.info("查询到{}条审批任务", taskApprovalStatuses.size());

        return taskApprovalStatuses.stream()
                .map(entity -> {
                    // 创建新的DTO对象并设置所有字段
                    TaskApprovalWithRawDataDTO dto = new TaskApprovalWithRawDataDTO();
                    dto.setId(entity.getId());
                    dto.setTaskFlowId(entity.getTaskFlowId());
                    dto.setNodeId(entity.getNodeId());
                    dto.setStatus(entity.getStatus());
                    dto.setStatusText(getStatusText(entity.getStatus()));
                    dto.setApproverId(entity.getApproverId());
                    dto.setApproverName(entity.getApproverName());
                    
                    // 从 user 表获取 approverAuthId
                    if (entity.getApproverId() != null) {
                        try {
                            com.example.demo.entity.User user = userMapper.selectById(entity.getApproverId().intValue());
                            if (user != null && user.getAuthId() != null) {
                                dto.setApproverAuthId(user.getAuthId());
                                //log.info("为任务ID={}设置审批人认证ID={}", entity.getTaskId(), user.getAuthId());
                            } else {
                                dto.setApproverAuthId(null);
                                //log.warn("审批人ID={}没有找到对应的用户认证ID", entity.getApproverId());
                            }
                        } catch (Exception e) {
                            dto.setApproverAuthId(null);
                            //log.error("获取审批人认证ID失败，审批人ID={}，错误信息: {}", entity.getApproverId(), e.getMessage(), e);
                        }
                    } else {
                        dto.setApproverAuthId(null);
                        //log.warn("任务ID={}没有关联审批人ID", entity.getTaskId());
                    }
                    
                    dto.setComment(entity.getComment());
                    dto.setStartTime(entity.getStartTime());
                    dto.setEndTime(entity.getEndTime());
                    dto.setCreatedAt(entity.getCreatedAt());
                    dto.setUpdatedAt(entity.getUpdatedAt());
                    dto.setTaskId(entity.getTaskId());
                    dto.setDataSourceId(entity.getDataSourceId());
                    dto.setFlowId(entity.getFlowId());

                    // 从 process_config 表获取 flowName
                    if (entity.getFlowId() != null) {
                        try {
                            com.example.demo.entity.ProcessConfig processConfig = processConfigMapper
                                    .selectById(entity.getFlowId());
                            if (processConfig != null && processConfig.getName() != null) {
                                dto.setFlowName(processConfig.getName());
                                //log.info("为任务ID={}设置流程名称={}", entity.getTaskId(), processConfig.getName());
                            } else {
                                dto.setFlowName("未知流程");
                                //log.warn("流程ID={}没有找到对应的流程配置", entity.getFlowId());
                            }
                        } catch (Exception e) {
                            dto.setFlowName("获取失败");
                            //log.error("获取流程名称失败，流程ID={}，错误信息: {}", entity.getFlowId(), e.getMessage(), e);
                        }
                    }

                    // 从 process_node 表获取 nodeName 和 nodeContent
                    if (entity.getNodeId() != null) {
                        try {
                            ProcessNode processNode = processNodeMapper.selectById(entity.getNodeId());
                            if (processNode != null) {
                                // 设置 nodeName
                                if (processNode.getNodeName() != null) {
                                    dto.setNodeName(processNode.getNodeName());
                                    //log.info("为任务ID={}设置节点名称={}", entity.getTaskId(), processNode.getNodeName());
                                } else {
                                    dto.setNodeName("未知节点");
                                }

                                // 设置 nodeContent
                                if (processNode.getNodeContent() != null) {
                                    dto.setNodeContent(processNode.getNodeContent());
                                    //log.info("为任务ID={}设置实际nodeContent", entity.getTaskId());
                                } else {
                                    dto.setNodeContent("{\"test\": \"default-node-content\", \"nodeId\": " + entity.getNodeId() + "}");
                                    //log.warn("节点ID={}没有找到实际nodeContent，使用默认值", entity.getNodeId());
                                }
                            } else {
                                dto.setNodeName("未知节点");
                                dto.setNodeContent("{\"test\": \"default-node-content\", \"nodeId\": " + entity.getNodeId() + "}");
                                //log.warn("节点ID={}没有找到对应的节点配置", entity.getNodeId());
                            }
                        } catch (Exception e) {
                            dto.setNodeName("获取失败");
                            dto.setNodeContent("{}");
                            //log.error("获取节点信息失败，节点ID={}，错误信息: {}", entity.getNodeId(), e.getMessage(), e);
                        }
                    } else {
                        dto.setNodeName("无节点");
                        dto.setNodeContent("{}");
                        //log.warn("任务ID={}没有关联节点ID", entity.getTaskId());
                    }

                    // 从 task 表中获取实际的 rawData
                    NewTask task = newTaskMapper.selectById(entity.getTaskId());
                    if (task != null && task.getRawData() != null) {
                        dto.setRawData(task.getRawData());
                        //log.info("为任务ID={}设置实际rawData", entity.getTaskId());
                    } else {
                        // 如果没有获取到实际数据，使用默认值
                        dto.setRawData("{\"test\": \"default-data\", \"taskId\": " + entity.getTaskId() + "}");
                        //log.warn("任务ID={}没有找到实际rawData，使用默认值", entity.getTaskId());
                    }

                    // 从 data_source 表获取 extraFields
                    if (entity.getDataSourceId() != null) {
                        DataSource dataSource = dataSourceMapper.selectById(entity.getDataSourceId());
                        if (dataSource != null && dataSource.getExtraFields() != null) {
                            dto.setExtraFields(dataSource.getExtraFields());
                            //log.info("为任务ID={}设置实际extraFields", entity.getTaskId());
                        } else {
                            // 如果没有获取到实际数据，使用默认值
                            dto.setExtraFields("{\"test\": \"default-extra-fields\", \"dataSourceId\": " + entity.getDataSourceId() + "}");
                            //log.warn("数据源ID={}没有找到实际extraFields，使用默认值", entity.getDataSourceId());
                        }
                    } else {
                        // 如果没有数据源ID，设置为空JSON
                        dto.setExtraFields("{}");
                        //log.warn("任务ID={}没有关联数据源ID", entity.getTaskId());
                    }

                    // 根据 dataSourceId 获取任务类型信息
                    if (entity.getDataSourceId() != null) {
                        try {
                            List<com.example.demo.entity.TaskType> taskTypes = taskTypeMapper
                                    .selectByDataSourceId(entity.getDataSourceId());
                            if (taskTypes != null && !taskTypes.isEmpty()) {
                                com.example.demo.entity.TaskType taskType = taskTypes.get(0); // 取第一个任务类型
                                dto.setTaskType(taskType.getTaskTypeId());
                                dto.setTaskTypeName(taskType.getTaskName());
                                dto.setTaskDescription(taskType.getTaskDescription()); // 设置任务描述
                                //log.info("为任务ID={}设置任务类型信息 - ID: {}, 名称: {}, 描述: {}", entity.getTaskId(),
//                                        taskType.getTaskTypeId(), taskType.getTaskName(), taskType.getTaskDescription());
                            } else {
                                // 没有找到任务类型信息，使用默认值
                                dto.setTaskType(null);
                                dto.setTaskTypeName("未知类型");
                                dto.setTaskDescription("未知描述");
                                //log.warn("数据源ID={}没有找到对应的任务类型信息，使用默认值", entity.getDataSourceId());
                            }
                        } catch (Exception e) {
                            dto.setTaskType(null);
                            dto.setTaskTypeName("获取失败");
                            dto.setTaskDescription("获取失败");
                            //log.error("获取任务类型信息失败，数据源ID={}，错误信息: {}", entity.getDataSourceId(), e.getMessage(), e);
                        }
                    } else {
                        // 如果没有数据源ID，设置为默认值
                        dto.setTaskType(null);
                        dto.setTaskTypeName("无数据源");
                        dto.setTaskDescription("无数据源");
                        //log.warn("任务ID={}没有关联数据源ID，无法获取任务类型信息", entity.getTaskId());
                    }
        
                    //log.info("找到当前处理中的审批节点，节点ID={}, 审批人ID={}", 
//                            entity.getNodeId(), entity.getApproverId());
                    
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public long countTaskApprovalStatuses(Long taskId, Long flowId) {
        return taskApprovalStatusMapper.count(taskId, flowId);
    }

    @Override
    public TaskApprovalStatusDTO getTaskApprovalStatusById(Long id) {
        TaskApprovalStatus taskApprovalStatus = taskApprovalStatusMapper.selectById(id);
        if (taskApprovalStatus == null) {
            throw new BusinessException("审批状态不存在，ID：" + id);
        }
        TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(taskApprovalStatus);
        fillNameFields(dto, taskApprovalStatus);
        return dto;
    }

    @Override
    @Transactional
    public TaskApprovalStatusDTO createTaskApprovalStatus(CreateTaskApprovalStatusRequest request) {
        TaskApprovalStatus taskApprovalStatus = new TaskApprovalStatus();
        taskApprovalStatus.setTaskFlowId(request.getTaskFlowId());
        taskApprovalStatus.setNodeId(request.getNodeId());
        taskApprovalStatus.setStatus(request.getStatus() != null ? request.getStatus() : 0); // 默认待处理
        taskApprovalStatus.setApproverId(request.getApproverId());
        taskApprovalStatus.setApproverName(request.getApproverName());
        taskApprovalStatus.setComment(request.getComment());
        taskApprovalStatus.setStartTime(request.getStartTime());
        taskApprovalStatus.setEndTime(request.getEndTime());
        taskApprovalStatus.setTaskId(request.getTaskId());
        taskApprovalStatus.setDataSourceId(request.getDataSourceId());
        taskApprovalStatus.setFlowId(request.getFlowId());
        taskApprovalStatus.setCreatedAt(LocalDateTime.now());
        taskApprovalStatus.setUpdatedAt(LocalDateTime.now());

        int result = taskApprovalStatusMapper.insert(taskApprovalStatus);
        if (result == 0) {
            throw new BusinessException("审批状态创建失败");
        }
        TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(taskApprovalStatus);
        fillNameFields(dto, taskApprovalStatus);
        return dto;
    }

    @Override
    @Transactional
    public TaskApprovalStatusDTO updateTaskApprovalStatus(Long id, CreateTaskApprovalStatusRequest request) {
        TaskApprovalStatus existingTaskApprovalStatus = taskApprovalStatusMapper.selectById(id);
        if (existingTaskApprovalStatus == null) {
            throw new BusinessException("审批状态不存在，无法更新");
        }

        existingTaskApprovalStatus.setTaskFlowId(request.getTaskFlowId());
        existingTaskApprovalStatus.setNodeId(request.getNodeId());
        existingTaskApprovalStatus.setStatus(request.getStatus());
        existingTaskApprovalStatus.setApproverId(request.getApproverId());
        existingTaskApprovalStatus.setApproverName(request.getApproverName());
        existingTaskApprovalStatus.setComment(request.getComment());
        existingTaskApprovalStatus.setStartTime(request.getStartTime());
        existingTaskApprovalStatus.setEndTime(request.getEndTime());
        existingTaskApprovalStatus.setTaskId(request.getTaskId());
        existingTaskApprovalStatus.setDataSourceId(request.getDataSourceId());
        existingTaskApprovalStatus.setFlowId(request.getFlowId());
        existingTaskApprovalStatus.setUpdatedAt(LocalDateTime.now());

        int result = taskApprovalStatusMapper.updateById(existingTaskApprovalStatus);
        if (result == 0) {
            throw new BusinessException("审批状态更新失败");
        }
        TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(existingTaskApprovalStatus);
        fillNameFields(dto, existingTaskApprovalStatus);
        return dto;
    }

    @Override
    @Transactional
    public void deleteTaskApprovalStatus(Long id) {
        TaskApprovalStatus existingTaskApprovalStatus = taskApprovalStatusMapper.selectById(id);
        if (existingTaskApprovalStatus == null) {
            throw new BusinessException("审批状态不存在，无法删除");
        }

        int result = taskApprovalStatusMapper.deleteById(id);
        if (result == 0) {
            throw new BusinessException("审批状态删除失败");
        }
    }

    @Override
    @Transactional
    public int initializeTaskApprovalStatusByDataSource(Long dataSourceId) {
        //log.info("=== 开始为数据源ID: {} 初始化任务审批状态 ===", dataSourceId);

        // 参数验证
        if (dataSourceId == null) {
            //log.error("参数验证失败：dataSourceId 不能为空");
            throw new BusinessException("数据源ID不能为空");
        }
        //log.info("步骤1：参数验证通过，dataSourceId = {}", dataSourceId);

        try {
            // 1. 批量分发该数据源下的未分发任务
            //log.info("步骤2：开始批量分发未分发任务");

            //log.info("步骤2.1：调用 newTaskFlowService.batchDistributeTaskFlows(dataSourceId={})", dataSourceId);
            int distributedCount;
            try {
                distributedCount = newTaskFlowService.batchDistributeTaskFlows(dataSourceId);
                //log.info("步骤2.2：批量分发任务完成，分发数量 = {}", distributedCount);
            } catch (Exception e) {
                //log.error("步骤2.2：批量分发任务失败，错误信息: {}", e.getMessage(), e);
                throw e;
            }

            if (distributedCount == 0) {
                //log.info("步骤2.3：数据源ID: {} 下没有未分发的任务，流程结束", dataSourceId);
                return 0;
            }

            //log.info("步骤2.4：成功分发 {} 个任务", distributedCount);

            // 2. 获取该数据源下已分发的任务流程关系
            //log.info("步骤3：开始获取已分发的任务流程关系");
            //log.info("步骤3.1：调用 newTaskFlowService.getNewTaskFlows 获取数据源 {} 的任务流程关系", dataSourceId);
            List<NewTaskFlowDTO> taskFlows;
            try {
                // 获取该数据源下所有任务流程关系
                List<NewTaskFlowDTO> allTaskFlows = newTaskFlowService.getNewTaskFlows(0, Integer.MAX_VALUE, null,
                        null);
                taskFlows = allTaskFlows.stream()
                        .filter(tf -> dataSourceId.equals(tf.getDataSourceId()) && tf.getIsDistributed() != null
                                && tf.getIsDistributed())
                        .collect(Collectors.toList());
                //log.info("步骤3.2：获取已分发任务流程关系完成，数量 = {}", taskFlows.size());
            } catch (Exception e) {
                //log.error("步骤3.2：获取任务流程关系失败，错误信息: {}", e.getMessage(), e);
                throw e;
            }

            if (taskFlows.isEmpty()) {
                //log.warn("步骤3.3：没有找到数据源ID: {} 对应的已分发任务流程关系，流程结束", dataSourceId);
                return 0;
            }

            // 3. 为每个任务流程关系获取对应的流程节点并创建审批状态记录
            //log.info("步骤4：开始创建审批状态记录");
            List<TaskApprovalStatus> approvalStatusList = new ArrayList<>();
            int recordCount = 0;

            for (int i = 0; i < taskFlows.size(); i++) {
                NewTaskFlowDTO taskFlow = taskFlows.get(i);
                //log.info("步骤4.{}: 处理任务流程关系 - ID={}, TaskID={}, FlowID={}, DataSourceID={}",
//                        i + 1, taskFlow.getId(), taskFlow.getTaskId(), taskFlow.getFlowId(),
//                        taskFlow.getDataSourceId());

                // 获取该流程的所有节点
                //log.info("步骤4.{}.1：获取流程ID: {} 的节点信息", i + 1, taskFlow.getFlowId());
                List<ProcessNodeDTO> processNodes;
                try {
                    processNodes = processNodeService.getProcessNodes(taskFlow.getFlowId());
                    //log.info("步骤4.{}.2：获取流程节点完成，节点数量 = {}", i + 1, processNodes != null ? processNodes.size() : 0);
                } catch (Exception e) {
                    //log.error("步骤4.{}.2：获取流程节点失败，错误信息: {}", i + 1, e.getMessage(), e);
                    continue; // 跳过这个任务流程关系
                }

                if (processNodes == null || processNodes.isEmpty()) {
                    //log.warn("步骤4.{}.3：流程ID: {} 下没有配置节点，跳过", i + 1, taskFlow.getFlowId());
                    continue;
                }

                // 为该任务流程关系的每个节点创建审批状态记录
                for (int j = 0; j < processNodes.size(); j++) {
                    ProcessNodeDTO node = processNodes.get(j);
                    recordCount++;
                    //log.info("步骤4.{}.{}: 创建审批状态记录 - 任务流程ID={}, 节点ID={}, 节点名称={}",
//                            i + 1, j + 1, taskFlow.getId(), node.getId(), node.getNodeName());

                    TaskApprovalStatus approvalStatus = new TaskApprovalStatus();
                    approvalStatus.setTaskFlowId(taskFlow.getId());
                    approvalStatus.setNodeId(node.getId());
                    approvalStatus.setStatus(0); // 默认待处理
                    approvalStatus.setApproverId(null); // 处理人为空
                    approvalStatus.setApproverName(null); // 处理人姓名为空
                    approvalStatus.setComment(null);
                    approvalStatus.setStartTime(null);
                    approvalStatus.setEndTime(null);
                    approvalStatus.setTaskId(taskFlow.getTaskId());
                    approvalStatus.setDataSourceId(dataSourceId);
                    approvalStatus.setFlowId(taskFlow.getFlowId());
                    approvalStatus.setNodeOrder(node.getNodeOrder()); // 设置节点顺序
                    approvalStatus.setCreatedAt(LocalDateTime.now());
                    approvalStatus.setUpdatedAt(LocalDateTime.now());

                    approvalStatusList.add(approvalStatus);
//                    //log.debug("审批状态记录详情: TaskFlowID={}, NodeID={}, TaskID={}, DataSourceID={}, FlowID={}",
//                            approvalStatus.getTaskFlowId(), approvalStatus.getNodeId(),
//                            approvalStatus.getTaskId(), approvalStatus.getDataSourceId(), approvalStatus.getFlowId());
                }
            }

            //log.info("步骤4.总结：共创建 {} 条审批状态记录", approvalStatusList.size());

            // 4. 批量插入审批状态记录
            if (!approvalStatusList.isEmpty()) {
                //log.info("步骤5：开始批量插入审批状态记录，数量 = {}", approvalStatusList.size());
                try {
                    int insertedCount = taskApprovalStatusMapper.batchInsert(approvalStatusList);
                    //log.info("步骤5.1：批量插入完成，实际插入数量 = {}", insertedCount);

                    if (insertedCount != approvalStatusList.size()) {
                        //log.warn("步骤5.2：插入数量不匹配！期望插入 {} 条，实际插入 {} 条", approvalStatusList.size(), insertedCount);
                    }

                    //log.info("=== 成功为数据源ID: {} 分发任务并创建了 {} 条审批状态记录 ===", dataSourceId, insertedCount);
                    return insertedCount;
                } catch (Exception e) {
                    //log.error("步骤5.1：批量插入审批状态记录失败，错误信息: {}", e.getMessage(), e);
                    throw e;
                }
            } else {
                //log.warn("步骤5：没有审批状态记录需要插入");
            }

            return 0;

        } catch (Exception e) {
            //log.error("=== 为数据源ID: {} 初始化任务审批状态失败 ===", dataSourceId);
            //log.error("异常类型: {}", e.getClass().getSimpleName());
            //log.error("异常信息: {}", e.getMessage());
            //log.error("异常堆栈:", e);
            throw new BusinessException("初始化任务审批状态失败: " + e.getMessage());
        }
    }

    @Override
    public List<TaskApprovalStatusDTO> getTaskApprovalStatusesByTaskId(Long taskId) {
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper.selectByTaskId(taskId);
        return taskApprovalStatuses.stream()
                .map(entity -> {
                    TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(entity);
                    fillNameFields(dto, entity);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskApprovalStatusDTO> getTaskApprovalStatusesByFlowId(Long flowId) {
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper.selectByFlowId(flowId);
        return taskApprovalStatuses.stream()
                .map(entity -> {
                    TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(entity);
                    fillNameFields(dto, entity);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskApprovalStatusDTO> getTaskApprovalStatusesByApproverIdAndStatusProcessing(Long approverId) {
        //log.info("查询审批人ID={}的处理中审批任务", approverId);
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper
                .selectByApproverIdAndStatusProcessing(approverId);
        //log.info("查询到{}条审批任务", taskApprovalStatuses.size());
        return taskApprovalStatuses.stream()
                .map(entity -> {
                    TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(entity);
                    fillNameFields(dto, entity);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskApprovalStatusDTO> getTaskApprovalStatusesByApproverIdAndStatusApproved(Long approverId) {
        //log.info("查询审批人ID={}的已审批任务", approverId);
        List<TaskApprovalStatus> taskApprovalStatuses = taskApprovalStatusMapper
                .selectByApproverIdAndStatusApproved(approverId);
        //log.info("查询到{}条已审批任务", taskApprovalStatuses.size());
        return taskApprovalStatuses.stream()
                .map(entity -> {
                    TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(entity);
                    fillNameFields(dto, entity);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<TaskApprovalNodeDetailDTO> getTaskApprovalNodeDetailsByTaskId(Long taskId) {
        // 根据任务ID查询所有审批状态
        List<TaskApprovalStatus> approvalStatuses = taskApprovalStatusMapper.selectByTaskId(taskId);

        if (approvalStatuses.isEmpty()) {
            return new ArrayList<>();
        }

        List<TaskApprovalNodeDetailDTO> nodeDetails = new ArrayList<>();

        for (TaskApprovalStatus status : approvalStatuses) {
            TaskApprovalNodeDetailDTO nodeDetail = new TaskApprovalNodeDetailDTO();

            // 设置基本信息
            nodeDetail.setId(status.getId());
            nodeDetail.setTaskFlowId(status.getTaskFlowId());
            nodeDetail.setTaskId(status.getTaskId());
            nodeDetail.setDataSourceId(status.getDataSourceId());

            // 设置审批状态信息
            nodeDetail.setStatus(status.getStatus());
            nodeDetail.setStatusText(getStatusText(status.getStatus()));
            nodeDetail.setComment(status.getComment());
            nodeDetail.setStartTime(status.getStartTime());
            nodeDetail.setEndTime(status.getEndTime());
            nodeDetail.setCreatedAt(status.getCreatedAt());
            nodeDetail.setUpdatedAt(status.getUpdatedAt());

            // 设置节点信息
            if (status.getNodeId() != null) {
                ProcessNodeDTO node = processNodeService.getProcessNodeById(status.getNodeId());
                if (node != null) {
                    nodeDetail.setNodeId(node.getId());
                    nodeDetail.setNodeName(node.getNodeName());
                    nodeDetail.setNodeOrder(node.getNodeOrder());
                    nodeDetail.setDepartment(node.getDepartment());
                    nodeDetail.setRole(node.getRole());
                    nodeDetail.setNodeContent(node.getNodeContent() != null ? node.getNodeContent().toString() : null);
                    nodeDetail.setDepartmentId(node.getDepartmentId());
                    nodeDetail.setRoleId(node.getRoleId());
                }
            }

            // 设置审批人信息
            nodeDetail.setApproverId(status.getApproverId());
            nodeDetail.setApproverName(status.getApproverName());

            // 设置流程信息
            nodeDetail.setFlowId(status.getFlowId());

            nodeDetails.add(nodeDetail);
        }

        // 按节点顺序排序
        nodeDetails.sort((a, b) -> {
            Integer orderA = a.getNodeOrder() != null ? a.getNodeOrder() : 0;
            Integer orderB = b.getNodeOrder() != null ? b.getNodeOrder() : 0;
            return orderA.compareTo(orderB);
        });

        return nodeDetails;
    }

    @Override
    public TaskApprovalWithRawDataDTO getCurrentProcessingNodeByTaskId(Long taskId) {
        //log.info("根据任务ID={}获取当前正在执行审批的节点信息", taskId);
        
        // 查询该任务下状态为处理中(1)的审批节点
        List<TaskApprovalStatus> processingStatuses = taskApprovalStatusMapper.selectByTaskIdAndStatus(taskId, 1);
        
        if (processingStatuses.isEmpty()) {
            //log.warn("任务ID={}没有找到正在处理中的审批节点", taskId);
            throw new BusinessException("该任务当前没有正在处理中的审批节点");
        }
        
        if (processingStatuses.size() > 1) {
            //log.warn("任务ID={}存在多个处理中的审批节点，这可能是数据异常", taskId);
        }
        
        // 取第一个处理中的节点（通常应该只有一个）
        TaskApprovalStatus entity = processingStatuses.get(0);
        
        // 使用和 getTaskApprovalStatusesByApproverIdAndStatusProcessingWithRawData 相同的逻辑来构建 DTO
        TaskApprovalWithRawDataDTO dto = new TaskApprovalWithRawDataDTO();
        dto.setId(entity.getId());
        dto.setTaskFlowId(entity.getTaskFlowId());
        dto.setNodeId(entity.getNodeId());
        dto.setStatus(entity.getStatus());
        dto.setStatusText(getStatusText(entity.getStatus()));
        dto.setApproverId(entity.getApproverId());
        dto.setApproverName(entity.getApproverName());
        
        // 从 user 表获取 approverAuthId
        if (entity.getApproverId() != null) {
            try {
                com.example.demo.entity.User user = userMapper.selectById(entity.getApproverId().intValue());
                if (user != null && user.getAuthId() != null) {
                    dto.setApproverAuthId(user.getAuthId());
                    //log.info("为任务ID={}设置审批人认证ID={}", entity.getTaskId(), user.getAuthId());
                } else {
                    dto.setApproverAuthId(null);
                    //log.warn("审批人ID={}没有找到对应的用户认证ID", entity.getApproverId());
                }
            } catch (Exception e) {
                dto.setApproverAuthId(null);
                //log.error("获取审批人认证ID失败，审批人ID={}，错误信息: {}", entity.getApproverId(), e.getMessage(), e);
            }
        } else {
            dto.setApproverAuthId(null);
            //log.warn("任务ID={}没有关联审批人ID", entity.getTaskId());
        }
        
        dto.setComment(entity.getComment());
        dto.setStartTime(entity.getStartTime());
        dto.setEndTime(entity.getEndTime());
        dto.setCreatedAt(entity.getCreatedAt());
        dto.setUpdatedAt(entity.getUpdatedAt());
        dto.setTaskId(entity.getTaskId());
        dto.setDataSourceId(entity.getDataSourceId());
        dto.setFlowId(entity.getFlowId());

        // 从 process_config 表获取 flowName
        if (entity.getFlowId() != null) {
            try {
                com.example.demo.entity.ProcessConfig processConfig = processConfigMapper
                        .selectById(entity.getFlowId());
                if (processConfig != null && processConfig.getName() != null) {
                    dto.setFlowName(processConfig.getName());
                    //log.info("为任务ID={}设置流程名称={}", entity.getTaskId(), processConfig.getName());
                } else {
                    dto.setFlowName("未知流程");
                    //log.warn("流程ID={}没有找到对应的流程配置", entity.getFlowId());
                }
            } catch (Exception e) {
                dto.setFlowName("获取失败");
                //log.error("获取流程名称失败，流程ID={}，错误信息: {}", entity.getFlowId(), e.getMessage(), e);
            }
        }
        
        // 从 process_node 表获取 nodeName 和 nodeContent
        if (entity.getNodeId() != null) {
            try {
                ProcessNode processNode = processNodeMapper.selectById(entity.getNodeId());
                if (processNode != null) {
                    // 设置 nodeName
                    if (processNode.getNodeName() != null) {
                        dto.setNodeName(processNode.getNodeName());
                        //log.info("为任务ID={}设置节点名称={}", entity.getTaskId(), processNode.getNodeName());
                    } else {
                        dto.setNodeName("未知节点");
                    }

                    // 设置 nodeContent
                    if (processNode.getNodeContent() != null) {
                        dto.setNodeContent(processNode.getNodeContent());
                        //log.info("为任务ID={}设置实际nodeContent", entity.getTaskId());
                    } else {
                        dto.setNodeContent("{\"test\": \"default-node-content\", \"nodeId\": "
                                + entity.getNodeId() + "}");
                        //log.warn("节点ID={}没有找到实际nodeContent，使用默认值", entity.getNodeId());
                    }
                } else {
                    dto.setNodeName("未知节点");
                    dto.setNodeContent(
                            "{\"test\": \"default-node-content\", \"nodeId\": " + entity.getNodeId() + "}");
                    //log.warn("节点ID={}没有找到对应的节点配置", entity.getNodeId());
                }
            } catch (Exception e) {
                dto.setNodeName("获取失败");
                dto.setNodeContent("{}");
                //log.error("获取节点信息失败，节点ID={}，错误信息: {}", entity.getNodeId(), e.getMessage(), e);
            }
        } else {
            dto.setNodeName("无节点");
            dto.setNodeContent("{}");
            //log.warn("任务ID={}没有关联节点ID", entity.getTaskId());
        }

        // 从 task 表中获取实际的 rawData
        NewTask task = newTaskMapper.selectById(entity.getTaskId());
        if (task != null && task.getRawData() != null) {
            dto.setRawData(task.getRawData());
            //log.info("为任务ID={}设置实际rawData", entity.getTaskId());
        } else {
            // 如果没有获取到实际数据，使用默认值
            dto.setRawData("{\"test\": \"default-data\", \"taskId\": " + entity.getTaskId() + "}");
            //log.warn("任务ID={}没有找到实际rawData，使用默认值", entity.getTaskId());
        }

        // 从 data_source 表获取 extraFields
        if (entity.getDataSourceId() != null) {
            DataSource dataSource = dataSourceMapper.selectById(entity.getDataSourceId());
            if (dataSource != null && dataSource.getExtraFields() != null) {
                dto.setExtraFields(dataSource.getExtraFields());
                //log.info("为任务ID={}设置实际extraFields", entity.getTaskId());
            } else {
                // 如果没有获取到实际数据，使用默认值
                dto.setExtraFields("{\"test\": \"default-extra-fields\", \"dataSourceId\": "
                        + entity.getDataSourceId() + "}");
                //log.warn("数据源ID={}没有找到实际extraFields，使用默认值", entity.getDataSourceId());
            }
        } else {
            // 如果没有数据源ID，设置为空JSON
            dto.setExtraFields("{}");
            //log.warn("任务ID={}没有关联数据源ID", entity.getTaskId());
        }

        // 根据 dataSourceId 获取任务类型信息
        if (entity.getDataSourceId() != null) {
            try {
                List<com.example.demo.entity.TaskType> taskTypes = taskTypeMapper
                        .selectByDataSourceId(entity.getDataSourceId());
                if (taskTypes != null && !taskTypes.isEmpty()) {
                    com.example.demo.entity.TaskType taskType = taskTypes.get(0); // 取第一个任务类型
                    dto.setTaskType(taskType.getTaskTypeId());
                    dto.setTaskTypeName(taskType.getTaskName());
                    dto.setTaskDescription(taskType.getTaskDescription()); // 设置任务描述
                    //log.info("为任务ID={}设置任务类型信息 - ID: {}, 名称: {}, 描述: {}", entity.getTaskId(),
//                            taskType.getTaskTypeId(), taskType.getTaskName(), taskType.getTaskDescription());
                } else {
                    // 没有找到任务类型信息，使用默认值
                    dto.setTaskType(null);
                    dto.setTaskTypeName("未知类型");
                    dto.setTaskDescription("未知描述");
                    //log.warn("数据源ID={}没有找到对应的任务类型信息，使用默认值", entity.getDataSourceId());
                }
            } catch (Exception e) {
                dto.setTaskType(null);
                dto.setTaskTypeName("获取失败");
                dto.setTaskDescription("获取失败");
                //log.error("获取任务类型信息失败，数据源ID={}，错误信息: {}", entity.getDataSourceId(), e.getMessage(), e);
            }
        } else {
            // 如果没有数据源ID，设置为默认值
            dto.setTaskType(null);
            dto.setTaskTypeName("无数据源");
            dto.setTaskDescription("无数据源");
            //log.warn("任务ID={}没有关联数据源ID，无法获取任务类型信息", entity.getTaskId());
        }
        
        //log.info("找到当前处理中的审批节点，节点ID={}, 审批人ID={}", 
//                entity.getNodeId(), entity.getApproverId());
        
        return dto;
    }

    @Override
    @Transactional
    public TaskApprovalStatusDTO forwardTask(ForwardTaskRequest request) {
        //log.info("转发任务开始，审批状态ID={}", request.getTaskApprovalStatusId());

        // 1. 参数验证
        if (request.getTaskApprovalStatusId() == null) {
            //log.error("无效的参数：审批状态ID不能为空");
            throw new BusinessException("审批状态ID不能为空");
        }
        
        if (request.getCurrentApproverId() == null) {
            //log.error("无效的参数：当前审批人ID不能为空");
            throw new BusinessException("当前审批人ID不能为空");
        }
        
        if (request.getNewApproverId() == null) {
            //log.error("无效的参数：新审批人ID不能为空");
            throw new BusinessException("新审批人ID不能为空");
        }

        // 2. 获取当前审批任务状态
        TaskApprovalStatus currentApprovalStatus = taskApprovalStatusMapper
                .selectById(request.getTaskApprovalStatusId());
        if (currentApprovalStatus == null) {
            //log.error("审批状态不存在，ID: {}", request.getTaskApprovalStatusId());
            throw new BusinessException("审批状态不存在，无法完成转发");
        }

        // 3. 更新当前审批任务状态为已转发(5)
        currentApprovalStatus.setStatus(5); // 5表示已转发
        currentApprovalStatus.setComment(request.getComment());
        currentApprovalStatus.setApproverId(request.getCurrentApproverId());
        currentApprovalStatus.setApproverName(request.getCurrentApproverName());
        currentApprovalStatus.setEndTime(LocalDateTime.now());
        currentApprovalStatus.setUpdatedAt(LocalDateTime.now());

        int updateResult = taskApprovalStatusMapper.updateById(currentApprovalStatus);
        if (updateResult == 0) {
            //log.error("更新审批状态失败，ID: {}", request.getTaskApprovalStatusId());
            throw new BusinessException("转发失败，请重试");
        }

        //log.info("审批状态更新成功，ID: {}，状态设置为已转发(5)", request.getTaskApprovalStatusId());

        // 4. 创建新的审批任务记录，复制当前记录的大部分字段
        TaskApprovalStatus newApprovalStatus = new TaskApprovalStatus();
        newApprovalStatus.setTaskFlowId(currentApprovalStatus.getTaskFlowId());
        newApprovalStatus.setNodeId(currentApprovalStatus.getNodeId());
        newApprovalStatus.setStatus(1); // 1表示处理中
        newApprovalStatus.setApproverId(request.getNewApproverId());
        newApprovalStatus.setApproverName(request.getNewApproverName());
        newApprovalStatus.setComment(null); // 新记录没有意见
        newApprovalStatus.setStartTime(LocalDateTime.now());
        newApprovalStatus.setEndTime(null);
        newApprovalStatus.setCreatedAt(LocalDateTime.now());
        newApprovalStatus.setUpdatedAt(LocalDateTime.now());
        newApprovalStatus.setTaskId(currentApprovalStatus.getTaskId());
        newApprovalStatus.setDataSourceId(currentApprovalStatus.getDataSourceId());
        newApprovalStatus.setFlowId(currentApprovalStatus.getFlowId());
        newApprovalStatus.setNodeOrder(currentApprovalStatus.getNodeOrder());

        int insertResult = taskApprovalStatusMapper.insert(newApprovalStatus);
        if (insertResult == 0) {
            //log.error("创建新审批状态失败");
            throw new BusinessException("转发失败，创建新审批记录失败");
        }

        //log.info("新审批状态创建成功，ID: {}，分配给审批人ID: {}", 
//                newApprovalStatus.getId(), request.getNewApproverId());

        // 5. 检查并更新任务的is_complete状态
        checkAndUpdateTaskCompleteStatus(currentApprovalStatus.getTaskId());

        // 6. 返回新创建的审批状态DTO
        TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(newApprovalStatus);
        fillNameFields(dto, newApprovalStatus);
        return dto;
    }
    
    /**
     * 检查并更新任务的完成状态
     * 如果所有审批节点都已完成，则将任务的is_complete设置为1
     */
    private void checkAndUpdateTaskCompleteStatus(Long taskId) {
        //log.info("检查任务ID: {} 的所有审批节点是否都已完成", taskId);

        // 获取任务的所有审批节点
        List<TaskApprovalStatus> allTaskApprovals = taskApprovalStatusMapper.selectByTaskId(taskId);
        //log.info("任务ID: {} 的审批节点总数: {}", taskId, allTaskApprovals.size());

        // 记录每个节点的状态信息用于调试
        for (TaskApprovalStatus approval : allTaskApprovals) {
            //log.info("节点ID: {}, 节点顺序: {}, 状态: {}", approval.getId(), approval.getNodeOrder(), approval.getStatus());
        }

        // 判断是否所有审批节点都已完成（状态为2-已通过、3-已拒绝、4-已跳过或5-已转发）
        boolean allCompleted = allTaskApprovals.stream()
                .allMatch(t -> t.getStatus() == 2 || t.getStatus() == 3 || t.getStatus() == 4 || t.getStatus() == 5);
        //log.info("任务ID: {} 是否所有节点都已完成: {}", taskId, allCompleted);

        if (allCompleted) {
            // 尝试更新任务完成状态
            try {
                NewTask task = newTaskMapper.selectById(taskId);
                //log.info("是否找到任务对象: {}, 任务当前完成状态: {}", task != null, task != null ? task.getIsComplete() : "N/A");
                if (task != null) {
                    //log.info("准备直接更新任务对象的完成状态，任务ID: {}", taskId);
                    // 直接设置isComplete为1，并确保该值不为null
                    Integer completeStatus = 1;
                    task.setIsComplete(completeStatus);
                    task.setUpdatedAt(LocalDateTime.now());
                    //log.info("设置任务完成状态为: {}, 任务ID: {}", completeStatus, taskId);
                    
                    int result = newTaskMapper.updateById(task);
                    //log.info("直接调用newTaskMapper.updateById更新任务完成状态，结果: {}, 任务ID: {}", result, taskId);
                    if (result > 0) {
                        //log.info("任务已完成，直接更新任务完成状态成功，任务ID: {}", taskId);
                    } else {
                        //log.warn("任务完成状态更新失败，任务ID: {}", taskId);
                    }
                } else {
                    //log.warn("未找到任务对象，无法更新完成状态，任务ID: {}", taskId);
                }
            } catch (Exception e) {
                //log.error("更新任务完成状态失败，任务ID: {}，错误信息: {}", taskId, e.getMessage(), e);
            }
        }
    }

    @Transactional
    public TaskApprovalStatusDTO approveTask(ApproveTaskRequest request) {
        //log.info("审批任务开始，审批状态ID={}，审批状态={}", request.getTaskApprovalStatusId(), request.getStatus());

        // 1. 参数验证 - 检查状态值是否有效
        Integer status = request.getStatus();
        if (status != 2 && status != 3 && status != 4 && status != 5) {
            //log.error("无效的审批状态值: {}", status);
            throw new BusinessException("审批状态无效，只能是2(通过)、3(拒绝)、4(跳过)或5(已转发)");
        }

        // 2. 获取当前审批任务状态
        TaskApprovalStatus currentApprovalStatus = taskApprovalStatusMapper
                .selectById(request.getTaskApprovalStatusId());
        if (currentApprovalStatus == null) {
            //log.error("审批状态不存在，ID: {}", request.getTaskApprovalStatusId());
            throw new BusinessException("审批状态不存在，无法完成审批");
        }

        // 3. 更新当前审批任务状态
        currentApprovalStatus.setStatus(status); // 使用传入的状态值
        currentApprovalStatus.setComment(request.getComment());
        currentApprovalStatus.setApproverId(request.getApproverId());
        currentApprovalStatus.setApproverName(request.getApproverName());
        currentApprovalStatus.setEndTime(LocalDateTime.now());
        currentApprovalStatus.setUpdatedAt(LocalDateTime.now());

        int updateResult = taskApprovalStatusMapper.updateById(currentApprovalStatus);
        if (updateResult == 0) {
            //log.error("更新审批状态失败，ID: {}", request.getTaskApprovalStatusId());
            throw new BusinessException("审批失败，请重试");
        }

        //log.info("审批状态更新成功，ID: {}，状态设置为{}", 
//                request.getTaskApprovalStatusId(),
//                status == 2 ? "已通过(2)" : status == 3 ? "已拒绝(3)" : status == 4 ? "已跳过(4)" : "已转发(5)");

        // 4. 根据状态执行不同的后续处理
        Long taskFlowId = currentApprovalStatus.getTaskFlowId();
        Integer currentNodeOrder = currentApprovalStatus.getNodeOrder();

        // 获取当前任务流程下的所有节点
        List<TaskApprovalStatus> allStatuses = taskApprovalStatusMapper.selectByTaskFlowId(taskFlowId);

        if (status == 2 || status == 4 || status == 5) { // 已通过、已跳过或已转发，处理下一个节点
            // 查找相同任务流程下，节点顺序比当前大1的节点
            TaskApprovalStatus nextApprovalStatus = allStatuses.stream()
                    .filter(s -> s.getNodeOrder().equals(currentNodeOrder + 1))
                    .findFirst()
                    .orElse(null);

            if (nextApprovalStatus != null) { // 不管当前状态是什么，都更新为处理中
                // 更新下一个节点状态为处理中(1)
                nextApprovalStatus.setStatus(1); // 处理中
                nextApprovalStatus.setStartTime(LocalDateTime.now());
                nextApprovalStatus.setUpdatedAt(LocalDateTime.now());

                int nextUpdateResult = taskApprovalStatusMapper.updateById(nextApprovalStatus);
                if (nextUpdateResult > 0) {
                    //log.info("下一个节点状态更新成功，节点ID: {}，状态设置为处理中(1)", nextApprovalStatus.getId());
                } else {
                    //log.warn("下一个节点状态更新失败，节点ID: {}", nextApprovalStatus.getId());
                }
            } else {
                //log.info("当前已是最后一个审批节点，无需更新下一个节点状态");
            }
        } else if (status == 3) { // 已拒绝，处理上一个节点
            // 查找相同任务流程下，节点顺序比当前小1的节点
            TaskApprovalStatus prevApprovalStatus = allStatuses.stream()
                    .filter(s -> s.getNodeOrder().equals(currentNodeOrder - 1))
                    .findFirst()
                    .orElse(null);

            if (prevApprovalStatus != null) {
                // 更新上一个节点状态为处理中(1)
                prevApprovalStatus.setStatus(1); // 处理中
                prevApprovalStatus.setUpdatedAt(LocalDateTime.now());

                int prevUpdateResult = taskApprovalStatusMapper.updateById(prevApprovalStatus);
                if (prevUpdateResult > 0) {
                    //log.info("上一个节点状态更新成功，节点ID: {}，状态设置为处理中(1)", prevApprovalStatus.getId());
                } else {
                    //log.warn("上一个节点状态更新失败，节点ID: {}", prevApprovalStatus.getId());
                }
            } else {
                //log.info("当前已是第一个审批节点，没有上一个节点可返回");
            }
        }

        // 每次审批完成后，检查该任务的所有审批节点是否都已完成
        checkAndUpdateTaskCompleteStatus(currentApprovalStatus.getTaskId());

        TaskApprovalStatusDTO dto = TaskApprovalStatusDTO.fromEntity(currentApprovalStatus);
        fillNameFields(dto, currentApprovalStatus);
        return dto;
    }

    @Override
    public UserTaskStatisticsDTO getUserTaskStatistics(Long userId) {
        //log.info("根据用户ID={}获取任务统计信息", userId);
        
        // 创建返回对象
        UserTaskStatisticsDTO statisticsDTO = new UserTaskStatisticsDTO();
        
        // 获取用户基本信息
        User user = userMapper.selectById(userId.intValue());
        if (user != null) {
            statisticsDTO.setUserId(userId);
            statisticsDTO.setUserName(user.getUserName());
            statisticsDTO.setUserAuthId(user.getAuthId());
        } else {
            //log.warn("未找到用户ID={}的用户信息", userId);
            statisticsDTO.setUserId(userId);
            statisticsDTO.setUserName("未知用户");
            statisticsDTO.setUserAuthId("未知认证ID");
        }
        
        // 获取用户的所有任务（作为审批人）
        List<TaskApprovalStatus> allTasks = taskApprovalStatusMapper.selectByApproverIdAndStatusProcessing(userId);
        allTasks.addAll(taskApprovalStatusMapper.selectByApproverIdAndStatusApproved(userId));
        
        // 统计任务数量
        int totalTasks = allTasks.size();
        int completedTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 2) // 已通过状态
                .count();
        int remainingTasks = totalTasks - completedTasks;
        
        statisticsDTO.setTotalTasks(totalTasks);
        statisticsDTO.setCompletedTasks(completedTasks);
        statisticsDTO.setRemainingTasks(remainingTasks);
        
        // 转换任务列表为 DTO
        List<TaskApprovalWithRawDataDTO> taskList = allTasks.stream()
                .map(entity -> {
                    // 使用和 getTaskApprovalStatusesByApproverIdAndStatusProcessingWithRawData 相同的逻辑来构建 DTO
                    TaskApprovalWithRawDataDTO dto = new TaskApprovalWithRawDataDTO();
                    dto.setId(entity.getId());
                    dto.setTaskFlowId(entity.getTaskFlowId());
                    dto.setNodeId(entity.getNodeId());
                    dto.setStatus(entity.getStatus());
                    dto.setStatusText(getStatusText(entity.getStatus()));
                    dto.setApproverId(entity.getApproverId());
                    dto.setApproverName(entity.getApproverName());
                    
                    // 从 user 表获取 approverAuthId
                    if (entity.getApproverId() != null) {
                        try {
                            com.example.demo.entity.User taskUser = userMapper.selectById(entity.getApproverId().intValue());
                            if (taskUser != null && taskUser.getAuthId() != null) {
                                dto.setApproverAuthId(taskUser.getAuthId());
                            } else {
                                dto.setApproverAuthId(null);
                            }
                        } catch (Exception e) {
                            dto.setApproverAuthId(null);
                            //log.error("获取审批人认证ID失败，审批人ID={}，错误信息: {}", entity.getApproverId(), e.getMessage(), e);
                        }
                    } else {
                        dto.setApproverAuthId(null);
                    }
                    
                    dto.setComment(entity.getComment());
                    dto.setStartTime(entity.getStartTime());
                    dto.setEndTime(entity.getEndTime());
                    dto.setCreatedAt(entity.getCreatedAt());
                    dto.setUpdatedAt(entity.getUpdatedAt());
                    dto.setTaskId(entity.getTaskId());
                    dto.setDataSourceId(entity.getDataSourceId());
                    dto.setFlowId(entity.getFlowId());

                    // 从 process_config 表获取 flowName
                    if (entity.getFlowId() != null) {
                        try {
                            com.example.demo.entity.ProcessConfig processConfig = processConfigMapper
                                    .selectById(entity.getFlowId());
                            if (processConfig != null && processConfig.getName() != null) {
                                dto.setFlowName(processConfig.getName());
                            } else {
                                dto.setFlowName("未知流程");
                            }
                        } catch (Exception e) {
                            dto.setFlowName("获取失败");
                            //log.error("获取流程名称失败，流程ID={}，错误信息: {}", entity.getFlowId(), e.getMessage(), e);
                        }
                    }
                    
                    // 从 process_node 表获取 nodeName 和 nodeContent
                    if (entity.getNodeId() != null) {
                        try {
                            ProcessNode processNode = processNodeMapper.selectById(entity.getNodeId());
                            if (processNode != null) {
                                // 设置 nodeName
                                if (processNode.getNodeName() != null) {
                                    dto.setNodeName(processNode.getNodeName());
                                } else {
                                    dto.setNodeName("未知节点");
                                }

                                // 设置 nodeContent
                                if (processNode.getNodeContent() != null) {
                                    dto.setNodeContent(processNode.getNodeContent());
                                } else {
                                    dto.setNodeContent("{\"test\": \"default-node-content\", \"nodeId\": " + entity.getNodeId() + "}");
                                }
                            } else {
                                dto.setNodeName("未知节点");
                                dto.setNodeContent("{\"test\": \"default-node-content\", \"nodeId\": " + entity.getNodeId() + "}");
                            }
                        } catch (Exception e) {
                            dto.setNodeName("获取失败");
                            dto.setNodeContent("{}");
                            //log.error("获取节点信息失败，节点ID={}，错误信息: {}", entity.getNodeId(), e.getMessage(), e);
                        }
                    } else {
                        dto.setNodeName("无节点");
                        dto.setNodeContent("{}");
                    }

                    // 从 task 表中获取实际的 rawData
                    NewTask task = newTaskMapper.selectById(entity.getTaskId());
                    if (task != null && task.getRawData() != null) {
                        dto.setRawData(task.getRawData());
                    } else {
                        // 如果没有获取到实际数据，使用默认值
                        dto.setRawData("{\"test\": \"default-data\", \"taskId\": " + entity.getTaskId() + "}");
                    }

                    // 从 data_source 表获取 extraFields
                    if (entity.getDataSourceId() != null) {
                        DataSource dataSource = dataSourceMapper.selectById(entity.getDataSourceId());
                        if (dataSource != null && dataSource.getExtraFields() != null) {
                            dto.setExtraFields(dataSource.getExtraFields());
                        } else {
                            // 如果没有获取到实际数据，使用默认值
                            dto.setExtraFields("{\"test\": \"default-extra-fields\", \"dataSourceId\": " + entity.getDataSourceId() + "}");
                        }
                    } else {
                        // 如果没有数据源ID，设置为空JSON
                        dto.setExtraFields("{}");
                    }

                    // 根据 dataSourceId 获取任务类型信息
                    if (entity.getDataSourceId() != null) {
                        try {
                            List<com.example.demo.entity.TaskType> taskTypes = taskTypeMapper
                                    .selectByDataSourceId(entity.getDataSourceId());
                            if (taskTypes != null && !taskTypes.isEmpty()) {
                                com.example.demo.entity.TaskType taskType = taskTypes.get(0); // 取第一个任务类型
                                dto.setTaskType(taskType.getTaskTypeId());
                                dto.setTaskTypeName(taskType.getTaskName());
                                dto.setTaskDescription(taskType.getTaskDescription());
                            } else {
                                // 没有找到任务类型信息，使用默认值
                                dto.setTaskType(null);
                                dto.setTaskTypeName("未知类型");
                                dto.setTaskDescription("未知描述");
                            }
                        } catch (Exception e) {
                            dto.setTaskType(null);
                            dto.setTaskTypeName("获取失败");
                            dto.setTaskDescription("获取失败");
                            //log.error("获取任务类型信息失败，数据源ID={}，错误信息: {}", entity.getDataSourceId(), e.getMessage(), e);
                        }
                    } else {
                        // 如果没有数据源ID，设置为默认值
                        dto.setTaskType(null);
                        dto.setTaskTypeName("无数据源");
                        dto.setTaskDescription("无数据源");
                    }
                    
                    return dto;
                })
                .collect(Collectors.toList());
        
        statisticsDTO.setTaskList(taskList);
        
        //log.info("用户ID={}的任务统计信息：总任务数={}，已完成={}，剩余={}", 
//                userId, totalTasks, completedTasks, remainingTasks);
        
        return statisticsDTO;
    }

    @Override
    public DataSourceUserStatisticsDTO getDataSourceUserStatistics(Long dataSourceId) {
        //log.info("根据数据源ID={}获取用户审批统计信息", dataSourceId);
        
        // 创建返回对象
        DataSourceUserStatisticsDTO statisticsDTO = new DataSourceUserStatisticsDTO();
        
        // 获取数据源信息
        DataSource dataSource = dataSourceMapper.selectById(dataSourceId);
        if (dataSource != null) {
            statisticsDTO.setDataSourceId(dataSourceId);
            statisticsDTO.setDataSourceName(dataSource.getName());
        } else {
            statisticsDTO.setDataSourceId(dataSourceId);
            statisticsDTO.setDataSourceName("未知数据源");
        }
        
        // 获取该数据源下的所有任务审批状态
        List<TaskApprovalStatus> allTasks = taskApprovalStatusMapper.selectByDataSourceId(dataSourceId);
        
        // 统计整体任务信息
        int totalTasks = allTasks.size();
        int completedTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 2) // 已通过状态
                .count();
        int processingTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 1) // 处理中状态
                .count();
        int pendingTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 0) // 待处理状态
                .count();
        
        statisticsDTO.setTotalTasks(totalTasks);
        statisticsDTO.setCompletedTasks(completedTasks);
        statisticsDTO.setProcessingTasks(processingTasks);
        statisticsDTO.setPendingTasks(pendingTasks);
        
        // 按用户分组统计
        Map<Long, List<TaskApprovalStatus>> tasksByUser = allTasks.stream()
                .filter(task -> task.getApproverId() != null)
                .collect(Collectors.groupingBy(TaskApprovalStatus::getApproverId));
        
        // 转换为用户审批统计列表
        List<UserApprovalStatisticsDTO> userStatistics = tasksByUser.entrySet().stream()
                .map(entry -> {
                    Long userId = entry.getKey();
                    List<TaskApprovalStatus> userTasks = entry.getValue();
                    
                    UserApprovalStatisticsDTO userStat = new UserApprovalStatisticsDTO();
                    
                    // 获取用户基本信息
                    User user = userMapper.selectById(userId.intValue());
                    if (user != null) {
                        userStat.setUserId(userId);
                        userStat.setUserName(user.getUserName());
                        userStat.setUserAuthId(user.getAuthId());
                    } else {
                        userStat.setUserId(userId);
                        userStat.setUserName("未知用户");
                        userStat.setUserAuthId("未知认证ID");
                    }
                    
                    // 统计该用户的任务信息
                    int userTotalTasks = userTasks.size();
                    int userCompletedTasks = (int) userTasks.stream()
                            .filter(task -> task.getStatus() != null && task.getStatus() == 2) // 已通过状态
                            .count();
                    int userProcessingTasks = (int) userTasks.stream()
                            .filter(task -> task.getStatus() != null && task.getStatus() == 1) // 处理中状态
                            .count();
                    int userPendingTasks = (int) userTasks.stream()
                            .filter(task -> task.getStatus() != null && task.getStatus() == 0) // 待处理状态
                            .count();
                    
                    userStat.setTotalTasks(userTotalTasks);
                    userStat.setCompletedTasks(userCompletedTasks);
                    userStat.setProcessingTasks(userProcessingTasks);
                    userStat.setPendingTasks(userPendingTasks);
                    
                    return userStat;
                })
                .collect(Collectors.toList());
        
        statisticsDTO.setUserStatistics(userStatistics);
        statisticsDTO.setTotalUsers(userStatistics.size());
        
        //log.info("数据源ID={}的用户审批统计信息：总用户数={}，总任务数={}，已完成={}，待处理={}，处理中={}", 
//                dataSourceId, userStatistics.size(), totalTasks, completedTasks, pendingTasks, processingTasks);
        
        return statisticsDTO;
    }

    @Override
    public DataSourceTaskStatisticsDTO getDataSourceTaskStatistics(Long dataSourceId) {
        //log.info("根据数据源ID={}获取任务统计信息", dataSourceId);
        
        // 创建返回对象
        DataSourceTaskStatisticsDTO statisticsDTO = new DataSourceTaskStatisticsDTO();
        
        // 获取数据源信息
        DataSource dataSource = dataSourceMapper.selectById(dataSourceId);
        if (dataSource != null) {
            statisticsDTO.setDataSourceId(dataSourceId);
            statisticsDTO.setDataSourceName(dataSource.getName());
        } else {
            statisticsDTO.setDataSourceId(dataSourceId);
            statisticsDTO.setDataSourceName("未知数据源");
        }
        
        // 获取该数据源下的所有任务审批状态
        List<TaskApprovalStatus> allTasks = taskApprovalStatusMapper.selectByDataSourceId(dataSourceId);
        
        // 统计各状态任务数
        int totalTasks = allTasks.size();
        int completedTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 2) // 已通过状态
                .count();
        int pendingTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 0) // 待处理状态
                .count();
        int processingTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 1) // 处理中状态
                .count();
        int rejectedTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 3) // 已拒绝状态
                .count();
        int skippedTasks = (int) allTasks.stream()
                .filter(task -> task.getStatus() != null && task.getStatus() == 4) // 已跳过状态
                .count();
        
        // 统计唯一任务数（按taskId分组）
        long totalUniqueTasks = allTasks.stream()
                .filter(task -> task.getTaskId() != null)
                .collect(Collectors.groupingBy(TaskApprovalStatus::getTaskId))
                .size();
        
        // 设置统计信息
        statisticsDTO.setTotalTasks(totalTasks);
        statisticsDTO.setCompletedTasks(completedTasks);
        statisticsDTO.setPendingTasks(pendingTasks);
        statisticsDTO.setProcessingTasks(processingTasks);
        statisticsDTO.setRejectedTasks(rejectedTasks);
        statisticsDTO.setSkippedTasks(skippedTasks);
        statisticsDTO.setTotalUniqueTasks((int) totalUniqueTasks);
        
        //log.info("数据源ID={}的任务统计信息：总任务数={}，已完成={}，待处理={}，处理中={}，已拒绝={}，已跳过={}，唯一任务数={}", 
//                dataSourceId, totalTasks, completedTasks, pendingTasks, processingTasks, rejectedTasks, skippedTasks, totalUniqueTasks);
//
        return statisticsDTO;
    }

    // 复制getStatusText方法到这里，避免依赖TaskApprovalStatusDTO的私有方法
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待处理";
            case 1: return "处理中";
            case 2: return "已通过";
            case 3: return "已拒绝";
            case 4: return "已跳过";
            case 5: return "已转发";
            default: return "未知";
        }
    }

    /**
     * 填充DTO中的name字段
     */
    private void fillNameFields(TaskApprovalStatusDTO dto, TaskApprovalStatus entity) {
        // 填充taskFlowName - 从NewTaskFlow表获取
        if (entity.getTaskFlowId() != null) {
            try {
                // 这里需要根据实际的NewTaskFlow实体来获取名称
                // 由于NewTaskFlow表中可能没有name字段，我们可以构造一个描述性名称
                dto.setTaskFlowName("任务流程-" + entity.getTaskFlowId());
            } catch (Exception e) {
                dto.setTaskFlowName("获取失败");
                //log.error("获取任务流程名称失败，TaskFlowID={}，错误信息: {}", entity.getTaskFlowId(), e.getMessage());
            }
        }

        // 填充nodeName - 从ProcessNode表获取
        if (entity.getNodeId() != null) {
            try {
                ProcessNode processNode = processNodeMapper.selectById(entity.getNodeId());
                if (processNode != null && processNode.getNodeName() != null) {
                    dto.setNodeName(processNode.getNodeName());
                } else {
                    dto.setNodeName("未知节点");
                    //log.warn("节点ID={}没有找到对应的节点配置", entity.getNodeId());
                }
            } catch (Exception e) {
                dto.setNodeName("获取失败");
                //log.error("获取节点名称失败，节点ID={}，错误信息: {}", entity.getNodeId(), e.getMessage());
            }
        }

        // 填充flowName - 从ProcessConfig表获取
        if (entity.getFlowId() != null) {
            try {
                com.example.demo.entity.ProcessConfig processConfig = processConfigMapper.selectById(entity.getFlowId());
                if (processConfig != null && processConfig.getName() != null) {
                    dto.setFlowName(processConfig.getName());
                } else {
                    dto.setFlowName("未知流程");
                    //log.warn("流程ID={}没有找到对应的流程配置", entity.getFlowId());
                }
            } catch (Exception e) {
                dto.setFlowName("获取失败");
                //log.error("获取流程名称失败，流程ID={}，错误信息: {}", entity.getFlowId(), e.getMessage());
            }
        }
    }
}